/**
 * Date & Time: 03/02/2015 - 03:59PM
 * @author Geoff
 * Description: JS File for PO. Needs to split on the view
 */
$(function () {
	
	$(".btn-approve-po").hide();

	$("input[name='po-id[]']").change(function(){
		if(this.checked){
			$(".btn-approve-po").show();
			$("input[name='purchase_order_product[" + this.value + "][]']").prop('checked', true);
		} else {
			$(".btn-approve-po").hide();
			$("input[name='purchase_order_product[" + this.value + "][]']").prop('checked', false);
		}

		});
	
	// Detect if atleast one checkbox is check and show Receive
	$(".po-product").change(function (e) {	
		var parent_po = $(this).parents('.list-row');
		var parent_cbx = parent_po.find('.list_po_id');
		var child_cbx = parent_po.find('.po-product').length;
		var child_cbx_checked =  parent_po.find('.po-product:checked').length;
		
		if ( child_cbx == child_cbx_checked ) 
			parent_cbx.prop('checked', true)
		 else 
			parent_cbx.prop('checked', false)
				
		if( child_cbx_checked > 0 )
			$(".btn-approve-po").show();
		else
			$(".btn-approve-po").hide();
		//console.log( $('#form_po_list').serialize() );
			
	});
	
	
	window.selected_items = window.selected_items || [];
	window.filters = window.filters || {};
	window.parent_selected_items = window.parent_selected_items || [];
	filters.vendor = $('select#filter_vendor').val();

	// Initial load, check selected
	for ( var i = 0; i < selected_items.length; i++ ) 
		$('input[value=' + selected_items[i] + ']').prop('checked', true);
	
	for ( var i = 0; i < parent_selected_items.length; i++ ) 
		$('input[value=' + parent_selected_items[i] + ']').prop('checked', true);
	
	//when filter is click it reset the selected_items
	$('#filter').on('click', function(e) {
			selected_items = [];
			parent_selected_items = [];
	});
	
	//automatically open the accordion
	
	if( selected_items.length ){
		$('.list-row').each(function(index, object) {
		
			if(Number($(object).find('.po-product:checked').size())) {
				$(object).find('.panel-collapse').removeClass("panel-collapse collapse").addClass("panel-collapse collapse in");
				//$(object).find('.panel-collapse').eq(index).removeClass("panel-collapse collapse").addClass("panel-collapse collapse in");			
			}
		});
	}
	
	$('.list_po_id').click(function(){
		$(this).parents('.list-row').find('input[name*=\'purchase_order_product\']').change();
	});
	
	// Add select/deselect event in item checkbox
	$('input[name*=\'purchase_order_product\']').on('change', function(e) {
		var item_id = e.target.value;
		toggleItem(item_id, $('input[value=' + item_id + ']'));
		
		//This is for parent check box
		var parent_so = $(this).parents('.list-row');
		var child_cbx = parent_so.find('.po-product').length;
		var child_cbx_checked =  parent_so.find('.po-product:checked').length;
		
		var parent_item_exists = false;
		var parent_item = $(this).parents('.list-row').find('.list_po_id');
		var parent_item_selected = parent_item.is(':checked');
		if( parent_selected_items.length ){
			$.each(parent_selected_items, function(index, value) { 
				if ( parent_item.val() == (value).toString() ) {
					parent_item_exists = true;
				}
			});
		}
		
		// SELECT FUNCTION AND EXISTED
		// Item exists and still selected? Do nothing.
		if(parent_item_exists && parent_item_selected ) return;
		
		// DESELECT FUNCTION AND EXISTED
		// Item exists in list and deselected? remove in list.
		if(parent_item_exists && !parent_item_selected) {
			parent_selected_items.splice( parent_selected_items.indexOf(parent_item.val()), 1);
			return;
		}
		
		// Remove parent checkbox checked when  Parent checkbox Item exists and child checkbox is not all checked
		if(parent_item_exists && child_cbx != child_cbx_checked ) {
			parent_selected_items.splice( parent_selected_items.indexOf(parent_item.val()), 1);
			return;
		}
	
		parent_selected_items.push(parent_item.val());
		

	});
	
	/** 
	 * Toggle item checkbox.
	 * @author AngelaMisa 02/18/2015
	 * @param item_id, elem
	 * @return void
	 */
	function toggleItem( id , item ) {

		var item_selected = item.is(':checked');
		var item_id = (id).toString();
		var item_exists = false;

		// Note: Workaround for InArray
		if ( selected_items.length ) {
			$.each(selected_items, function(index, value) { 
				if ( (id).toString() == (value).toString() ) {
					item_id = (value).toString();
					item_exists = true;
				}
			});
		}

		// SELECT FUNCTION AND EXISTED
		// Item exists and still selected? Do nothing.
		if ( item_exists && item_selected ) return;

		// DESELECT FUNCTION AND EXISTED
		// Item exists in list and deselected? remove in list.
		if ( item_exists && !item_selected ) {
			// Remove in Main Item list.
			selected_items.splice( selected_items.indexOf(item_id), 1);
			return;
		}

		// Add new Item in Main List
		selected_items.push(item_id);
	}
	
	// Preview of Voucher
	$(".preview-voucher").click(function(e){
		e.preventDefault();
		window.open($(this).attr('href'));
	});
	
	// Sends Mail including Voucher
	$(".send-voucher").click(function(e){
		$(".trace-po-" + po_item).html("");
		var po_item = $(this).attr("po-item");
		e.preventDefault();
		$.ajax({
			url: $(this).attr('href'),
			type: 'GET',
			beforeSend: function(){
				$(".trace-po-" + po_item).html('<h3><i class="fa fa-spinner fa-spin"></i></h3>');
			},
			success: function(){
				$(".trace-po-" + po_item).html("");
				$(".po-item-voucher-status-" + po_item).html("<i>Sent</i>");
				alert("Voucher has successfully send to email.");
			}
		});
	});
	
	// Edit of Voucher, shows form for editing voucher record details
	$(".edit-voucher").click(function(e){
		e.preventDefault();
		$.ajax({
			url: $(this).attr("href"),
			type: 'GET',
			error: function(){
				alert("It seems you need to view its voucher details first.");
			},
			beforeSend: function(){
				$("#general-modal .modal-dialog .modal-content").html('<h3><i class="fa fa-spinner fa-spin"></i></h3>');
			},
			success: function(html){
				$("#general-modal .modal-dialog .modal-content").html("");
				$("#general-modal .modal-dialog .modal-content").html(html);
			}
		});
	});
	
	/*$(".btn-approve-po").click(function(){
		var selected_po_id = $("input[name='po-id[]']:checked").map(function(){ return this.value }).get();
		var selected_pos = new Array();
		$.each(selected_po_id, function(key, value){
			selected_pos[value] = $("input[name='purchase_order_product[" + value + "][]']:checked").map(function(){ return this.value }).get();
			console.log(selected_pos[value]);
		});
		
		selected_pos = JSON.stringify(selected_pos);
		
		$.post($('base').attr('href') + '/po/approvePurchaseOrders', { selected_pos:selected_pos }, function(response){
			if(response.success == 1){
				alert("You have successfully move the PO(s) to received.");
				self.location = $('base').attr('href') + '/po';
			}
		}, 'json');
	});*/
	
	$("#export_so").click(function(){
		self.location = $('base').attr('href') + '/po/export-so/1?' + $("#form-filter").serialize();
		
	});
	
	$("#export_po_list").click(function(){
		self.location = $('base').attr('href') + '/po/export-list/1?' + $("#form-filter").serialize();
	});
	
	$("#approved_po").click(function(){
		$.ajax({
			url :$('base').attr('href') + '/po/approvePurchaseOrders',
			type: 'post',
			data: { 'ids': selected_items.join() } ,
			success: function(response){
				if(response){
				//alert(response);
				//self.location=$('base').attr('href')+'/po';
					$('#list-container').showList(document.URL);
				}
				else
					alert('not ok');
				
			}
			
			
		});
	});
});
/**
 * Moved rendering of PO Status upload here
 * @author Geoffrey 03/09/2015 - 10:24PM 
 */
renderUpload($("base").attr("href") + '/po/postUploadPurchaseOrderStatus', 'postUploadPurchaseOrderStatus');